import base64
import json
import sys
import os


def convert_to_base64(content):
    # 将字符串编码为字节流
    content_bytes = content.encode('utf-8')
    # 使用Base64进行编码
    base64_bytes = base64.b64encode(content_bytes)
    # 将编码后的字节流转换为字符串
    base64_string = base64_bytes.decode('utf-8')
    return base64_string


def base64Recover(content):
    content_bytes = content.encode('utf-8')
    RecoverContent = base64.b64decode(content_bytes).decode('utf-8')
    return RecoverContent


def encrypt(input_string):
    key = "131425"
    encrypted_string = ""
    key_index = 0
    try:
        for char in input_string:
            # 获取当前字符对应的ASCII码值
            ascii_value = ord(char)
            # 获取当前密钥字符对应的ASCII码值
            key_ascii = int(key[key_index])
            # 对当前字符进行加密
            if key_index % 2 == 0:
                encrypted_ascii = ascii_value + key_ascii
            else:
                encrypted_ascii = ascii_value - key_ascii
            # 将加密后的ASCII码值转换为字符
            encrypted_char = chr(encrypted_ascii)
            # 添加到加密后的字符串中
            encrypted_string += encrypted_char
            # 更新密钥索引，循环使用密钥
            key_index = (key_index + 1) % len(key)
    except Exception as e:
        print(e)
    return convert_to_base64(encrypted_string)


def decrypt(encrypted_string):
    key = "131425"
    decrypted_string = ""
    key_index = 0
    encrypted_string = base64Recover(encrypted_string)
    print(encrypted_string)
    try:
        for char in encrypted_string:
            # 获取当前字符对应的ASCII码值
            ascii_value = ord(char)

            # 获取当前密钥字符对应的ASCII码值
            key_ascii = int(key[key_index])

            # 对当前字符进行解密
            if key_index % 2 == 0:
                decrypted_ascii = ascii_value - key_ascii
            else:
                decrypted_ascii = ascii_value + key_ascii
            # 将解密后的ASCII码值转换为字符
            decrypted_char = chr(decrypted_ascii)

            # 添加到解密后的字符串中
            decrypted_string += decrypted_char

            # 更新密钥索引，循环使用密钥
            key_index = (key_index + 1) % len(key)
    except Exception as e:
        print(e)
    return decrypted_string


def InfoSaving(key, value):
    InfoJson = 'info.json'
    if not os.path.exists(InfoJson):
        Info = {}
    else:
        with open(InfoJson, "r", encoding='utf-8') as file:
            Info = json.load(file)
    Info[encrypt(key)] = encrypt(value)
    try:
        with open(InfoJson, "w+", encoding='utf-8') as file:
            json.dump(Info, file, ensure_ascii=False, indent=4)
        return True
    except Exception as E:
        return False


def InfoRead():
    InfoJson = 'info.json'
    if not os.path.exists(InfoJson):
        return {}
    with open(InfoJson, "r", encoding='utf-8') as file:
        Info = json.load(file)
    Infoencrypt = {}
    for key, value in Info.items():
        Infoencrypt[decrypt(key)] = decrypt(value)
    return Infoencrypt

if __name__ =="__main__":
    print(decrypt("WGZHZVJcdHB4a3Rf"))